from django.utils import timezone
from django.core.exceptions import ObjectDoesNotExist
from rest_framework.exceptions import ValidationError
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework_simplejwt.authentication import JWTAuthentication
from drf_yasg import openapi
from drf_yasg.utils import swagger_auto_schema

from apps.ExamManagement.models import Exam
from apps.ResultManagement.models import Results, ResultQuestionSolution
from .serializers import ResultsSerializer, ResultDetailSerializer
from ..UserManagement.models import User

from ..utils.pageNumberPagination import CustomPageNumberPagination
from ..utils.response_utils import api_response, ResponseCode


class ResultListView(APIView):
    """
    根据考试id查询答题卡列表
    """
    authentication_classes = [JWTAuthentication]
    permission_classes = [IsAuthenticated]
    pagination_class = CustomPageNumberPagination

    @swagger_auto_schema(
        operation_description="根据考试id查询答题卡列表",
        manual_parameters=[
            openapi.Parameter('exam_id', openapi.IN_QUERY, description="考试ID", type=openapi.TYPE_STRING),
        ],
        responses={
            200: ResultsSerializer(many=True),
            400: "请求参数错误",
            500: "服务器内部错误"
        },
        tags=['答题卡管理']
    )
    def get(self, request):
        try:
            exam_id = request.query_params.get("exam_id")
            try:
                exam = Exam.objects.get(id=exam_id)
            except ObjectDoesNotExist:
                return api_response(ResponseCode.NOT_FOUND, "考试不存在")
            results = Results.objects.filter(exam=exam).order_by('total_score')

            page_size = request.query_params.get("pageSize", 10)

            paginator = CustomPageNumberPagination()
            paginator.page_size = int(page_size)  # 每页的条数
            paginator.page_query_param = 'pageNo'  # 页码的参数名
            paginator.page_size_query_param = 'page_size'  # 每页数据条数的参数名

            result_page = paginator.paginate_queryset(results, request)
            serializer = ResultsSerializer(result_page, many=True)
            paginated_response = paginator.get_paginated_response(serializer.data)

            return api_response(ResponseCode.SUCCESS, '答题卡列表获取成功', paginated_response.data)

        except ValidationError as e:
            return api_response(ResponseCode.BAD_REQUEST, f"请求参数错误: {str(e)}")
        except Exception as e:
            return api_response(ResponseCode.INTERNAL_SERVER_ERROR, f"服务器内部错误: {str(e)}")


class ResultDetailView(APIView):
    """
    根据考试id查询答题卡详情
    """
    authentication_classes = [JWTAuthentication]
    permission_classes = [IsAuthenticated]

    @swagger_auto_schema(
        operation_description="根据考试id查询答题卡详情",
        manual_parameters=[
            openapi.Parameter('exam_id', openapi.IN_QUERY, description="考试id", type=openapi.TYPE_STRING),
            openapi.Parameter('user_id', openapi.IN_QUERY, description="用户id", type=openapi.TYPE_STRING),
        ],
        responses={
            200: ResultDetailSerializer(),
            404: "未找到信息",
            500: "服务器内部错误",
        },
        tags=['答题卡管理']
    )
    def get(self, request):
        try:
            exam_id = request.query_params.get("exam_id")
            user_id = request.query_params.get("user_id")
            exam = Exam.objects.filter(id=exam_id).first()
            if not exam:
                return api_response(ResponseCode.NOT_FOUND, "未找到该考试")
            user = User.objects.filter(id=user_id).first()
            if not user:
                return api_response(ResponseCode.NOT_FOUND, "未找到该用户")
            results = Results.objects.filter(exam=exam, user=user).order_by('-created_at').first()
            if not results:
                return api_response(ResponseCode.NOT_FOUND, "未找到该答题卡")

            serializer = ResultDetailSerializer(results)
            return api_response(ResponseCode.SUCCESS, '试卷详情获取成功', serializer.data)
        except ValidationError as e:
            return api_response(ResponseCode.BAD_REQUEST, f"请求参数错误: {str(e)}")
        except Exception as e:
            return api_response(ResponseCode.INTERNAL_SERVER_ERROR, f"服务器内部错误: {str(e)}")

